<template>
    <div class="detail" v-if="Object.keys(acinfo).length">
        <van-notice-bar color="#ffffff" background="#F17F2A" left-icon="underway-o">
            <p class="notice">
                <span>订单编号：{{order_info.toi_sn}}</span>
                <span>{{order_info.order_status_name}}</span>
            </p>
        </van-notice-bar>
        <div class="info">
            <h3 class="title">
                <span>订单详情</span>
            </h3>
            <ul class="infoList">
                <li>
                    <span class="label">活动信息：</span>
                    <span class="msg">{{acinfo.title}}</span>
                </li>
                <li>
                    <span class="label">姓名：</span>
                    <span class="msg">{{acinfo.toi_username}}</span>
                </li>
                <li>
                    <span class="label">手机号码：</span>
                    <span class="msg">{{acinfo.phone}}</span>
                </li>
                <li>
                    <span class="label">活动时间：</span>
                    <span class="msg">{{acinfo.date}}</span>
                </li>
                <li>
                    <span class="label">活动地点：</span>
                    <span class="msg">{{acinfo.place}}</span>
                </li>
                <li>
                    <span class="label">下单时间：</span>
                    <span class="msg">{{order_info.i_add_time}}</span>
                </li>
                <li>
                    <span class="label">门票张数：</span>
                    <span class="msg">{{total}}张</span>
                </li>
                <li>
                    <span class="label">门票明细：</span>
                    <div class="msg">
                        <p v-for="item in  acinfo.info" :key="item.price_id">
                            <span>{{item.name}} <span class="money">¥ {{item.price}}</span></span>
                            <span> ×{{item.num}}</span>
                        </p>
                    </div>
                </li>
                <li class="border0">
                    <span class="label">门票金额：</span>
                    <span class="msg money text-r">¥ {{order_info.order_amount>0?order_info.order_amount:0}}</span>
                </li>
                <li class="border0">
                    <span class="label ">优惠券：</span>
                    <span class="msg money text-r">- ¥ {{order_info.yh_price>0?order_info.yh_price:0}}</span>
                </li>
                <li class="border0">
                    <span class="label total">总计金额：</span>
                    <span class="msg money total">¥ {{order_info.order_amount>0?order_info.order_amount:0}}</span>
                </li>
            </ul>
        </div>
        <div :class="['qrcode',order_info.toi_status==1?'':'disabled'] ">
            <div class="left">
                <p>天士力大健康城参观门票</p>
                <p v-if="order_info.toi_status==1">验证码：{{order_info.toi_sn}}</p>
            </div>
            <div class="right" @click="showcode">
                <img src="../../../static/img/erweima.png" alt="">
            </div>
        </div>
        <div class="cancel">
            <!--            订单状态 1预约成功，2待支付，3已参加，4人员不足已取消，5已取消，6已退款 7未付款已取消 10已过期-->
            <div class="btn" v-if="order_info.toi_status==2" @click="gopay">立即支付（{{minutes}}分{{seconds}}秒）</div>
            <div class="btn " @click="cancelorder" v-if="order_info.toi_status==2">取消预约</div>
            <div class="btn " @click="cancelorder" v-else-if="order_info.toi_status==1&&order_info.can_refund">退票</div>
            <div class="btn cel" v-else-if="order_info.toi_status==3" @click="goagain">再次预约</div>
            <div class="btn " v-else @click="goindex">重新预约</div>

        </div>
        <van-overlay :show="show" :duration=".5">
            <div v-show="show" :class="['erweima']">
                <div class="content">
                    <p>天士力大健康城参观门票</p>
                    <p v-if="order_info.toi_status==1">验证码：{{order_info.toi_sn}}</p>
                    <div class="qr">
                        <vue-qrcode :value="order_info.toi_sn"/>
                    </div>
                </div>
                <div class="close" @click="show = false"></div>
            </div>
        </van-overlay>
    </div>
</template>

<script>
    import VueQrcode from 'vue-qrcode'
    import {Dialog} from 'vant';
    import {ActiveInfo, ActiveCancel, ActiveRefund, ActivePay} from '@/http/active'
    import wx from 'weixin-js-sdk'

    export default {
        name: 'orderdetail',
        components: {
            VueQrcode
        },
        data() {
            return {
                show: false,
                qrURL: '',
                titem_id: '',
                minutes: '',
                seconds: '',
                countTimer: null,
                loopTimer: null,
                acinfo: {},
                order_info: {},
                total: 0,
                orderTimer: null,
                orderStatusTimer: null
            }
        },
        created() {
            this.titem_id = this.$route.query.titem_id;
            if (this.$route.query.api_token) {
                localStorage.setItem('api_token', this.$route.query.api_token);
            } else if (localStorage.getItem('api_token')) {
                this._ActiveInfo()
            } else {
                this.$router.back()
            }
        },
        mounted() {
            this.$once('hook:beforeDestroy', () => {
                this.clearCountLoop();
                this.clearOrderStatusLoop();
            })
        },
        methods: {
            clearCountLoop() {
                //如果定时器在运行则关闭
                if (this.orderTimer) {
                    window.clearInterval(this.orderTimer);
                    this.orderTimer = null;
                }
            },
            /**
             * @清除订单状态轮询
             */
            clearOrderStatusLoop() {
                //如果定时器在运行则关闭
                if (this.orderStatusTimer) {
                    window.clearInterval(this.orderStatusTimer);
                    this.orderStatusTimer = null;
                }
            },
            _ActiveInfo() {
                this.total = 0;
                ActiveInfo(this.titem_id).then(res => {
                    if (res.status == 1) {
                        this.acinfo = res.data;
                        this.order_info = res.data.order_info;
                        let info = res.data.info;
                        info.map(item => {
                            this.total += Number(item.num)
                        })
                        if (this.order_info.toi_status == 2) {
                            this.atime(res.data.order_info.i_add_time)
                        }
                    }
                })
            },
            atime(timeval) {
                let v = this
                let time = new Date(timeval.replace(new RegExp("-", "gm"), "/")).getTime()
                let now = new Date().getTime()
                if ((now - time) < 30 * 60 * 1000) {
                    let timeDown = () => {
                        let now = new Date().getTime()
                        let leftTime = 1800000 - (now - time);
                        let mm = parseInt(leftTime / 1000 / 60 % 60, 10);
                        let ss = parseInt(leftTime / 1000 % 60, 10);
                        v.minutes = mm < 10 ? ('0' + mm) : mm;
                        v.seconds = ss < 10 ? ('0' + ss) : ss;
                        if (parseInt(v.minutes) <= 0 && parseInt(v.seconds) <= 0) {
                            v.clearTimeCount()
                            this.$dialog.alert({
                                title: '提示',
                                message: '您的订单超时未支付，请重新购票',
                            }).then(() => {
                                v.$router.back()
                            });
                            return;
                        }
                        return timeDown;
                    }
                    if (!v.countTimer) {
                        v.countTimer = setInterval(timeDown(), 1e3)
                    }
                } else {
                    this.$dialog.alert({
                        title: '提示',
                        message: '您的订单超时未支付，请重新购票',
                    }).then(() => {
                        v.$router.replace('/active/index');
                    });
                }
            },
            clearTimeCount() {
                if (this.countTimer) { //如果定时器在运行则关闭
                    window.clearInterval(this.countTimer);
                    this.countTimer = null;
                }
            },
            showcode() {
                if (this.order_info.toi_status == 1) {
                    this.show = true
                }
            },
            gopay() {
                ActivePay(this.titem_id, 2).then(res => {
                    if (res.status == 1) {
                        let mini = res.data.wxpayinfo;
                        if (mini.appId && mini.timeStamp && mini.nonceStr && mini.package && mini.signType && mini.paySign) {
                            this.orderStatusLoop()
                            let path = `/pages/pay/index?appId=${mini.appId}&timeStamp=${mini.timeStamp}&nonceStr=${mini.nonceStr}&package=${encodeURIComponent(mini.package)}&signType=${mini.signType}&paySign=${encodeURIComponent(mini.paySign)}`;
                            wx.miniProgram.navigateTo({
                                url: path
                            })
                        }
                    } else {
                        this.$toast(res.msg || '稍后再试')
                    }
                })
            },
            goindex() {
                this.$router.push('/active/index')
            },
            goagain() {
                this.$router.push({path: `/active/acDetail?active_id=${this.order_info.active_id}`})
            },
            cancelorder() {
                Dialog.confirm({
                    title: this.order_info.toi_status == 1 ? '退票' : '取消订单',
                    message: this.order_info.toi_status == 1 ? '是否确认退票？' : '是否确认取消订单？',
                })
                    .then(() => {
                        if (this.order_info.toi_status == 1 && this.order_info.can_refund) {
                            this._ActiveRefund()
                        } else if (this.order_info.toi_status == 2) {
                            this._ActiveCancel()
                        }
                    })
                    .catch(() => {
                        // on cancel
                    });
            },
            // 取消订单
            _ActiveCancel() {
                ActiveCancel(this.titem_id).then(res => {
                    if (res.status == 1) {
                        this.$toast('取消成功')
                    } else {
                        this.$toast(res.msg || '稍后再试')
                    }
                    this._ActiveInfo()
                })
            },
            // 退票
            _ActiveRefund() {
                ActiveRefund(this.titem_id).then(res => {
                    if (res.status == 1) {
                        this.$toast('退票成功')
                        this._ActiveInfo()
                    } else {
                        this.$toast(res.msg || '稍后再试')
                    }
                })
            },
            /**
             * 发起支付的同时轮询查询订单状态
             */
            orderStatusLoop() {
                // 防止重复开启轮询
                if (!this.orderStatusTimer) {
                    let fn = () => {
                        ActiveInfo(this.titem_id).then((res) => {
                            if (res.status == 1) {
                                if (res.data.order_info.toi_status == 1) {
                                    // 已完成支付跳转成功
                                    this.$router.replace({path: '/active/success', query: {'titem_id': this.titem_id}});
                                    return;
                                }
                            }
                        });
                        return fn;
                    }
                    this.orderStatusTimer = setInterval(fn(), 1e3);
                }
            },
        }
    }
</script>

<style lang="scss" scoped>

    .detail {
        width: 100vw;
        margin: 0 auto;
        min-height: 100vh;
        background: #EEEEEE;
        padding-bottom: 180px;

        /deep/ .van-notice-bar__content {
            width: 100%;

            .notice {
                width: 100%;
                display: flex;
                justify-content: space-between;
            }
        }

        .info {
            background: #ffffff;
            border-radius: 0 0 24px 24px;
            padding: 37px 30px;

            .title {
                span {
                    font-size: 32px;
                    font-weight: 500;
                    color: rgba(50, 50, 50, 1);
                    border-left: 6px solid #E60012;
                    text-indent: 30px;
                    display: inline-block;
                }
            }

            .infoList {
                // padding: 0 30px;
                margin-top: 28px;

                li {
                    border-bottom: 2px solid #EEEEEE;
                    line-height: 98px;
                    font-size: 30px;
                    font-weight: 500;
                    color: #323232;
                    display: flex;

                    .label {
                        margin-right: 70px;
                        width: 155px;
                        text-align: right;

                        &.total {
                            font-size: 32px;
                            width: 170px;
                        }
                    }

                    .msg {
                        color: #777777;
                        flex: 1;

                        p {
                            width: 100%;
                            display: flex;
                            justify-content: space-between;
                            color: #323232;

                            .money {
                                color: #E10028;
                            }
                        }

                        &.text-r {
                            text-align: right;
                        }

                        &.money {
                            color: #E10028;
                        }

                        &.total {
                            font-size: 36px;
                            font-weight: bold;
                        }
                    }

                    &.border0 {
                        border: 0;
                        line-height: 80px;
                    }
                }
            }
        }

        .qrcode {
            width: 750px;
            height: 160px;
            background: rgba(255, 255, 255, 1);
            border-radius: 24px;
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 30px;
            color: $fzColor;

            .left {
                font-size: 30px;
                font-weight: 500;
                line-height: 60px;
            }

            .right {
                width: 96px;
                height: 96px;
                background: url('../../../static/img/erweima.png') no-repeat center center;
                background-size: 100% 100%;
            }

            &.disabled {

                color: #C1C1C1;

                .right {
                    opacity: .5;
                }
            }
        }

        .cancel {
            margin-top: 72px;

            .btn {
                width: 520px;
                height: 78px;
                background: linear-gradient(90deg, rgba(241, 127, 42, 1), rgba(228, 114, 29, 1));
                border-radius: 39px;
                font-size: 34px;
                font-weight: 500;
                color: rgba(255, 255, 255, 1);
                line-height: 78px;
                text-align: center;
                margin: 0 auto 48px auto;

                &.cel {
                    border: 2px solid $calendarWeekColor;
                    background-color: transparent;
                    color: $calendarWeekColor;
                    margin: 0 auto;
                }
            }
        }

        .erweima {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;

            .content {
                width: 534px;
                height: 616px;
                background: url('../../../static/img/erweimadibu.png') no-repeat center center;
                background-size: 100% 100%;
                font-size: 30px;
                font-weight: 500;
                color: rgba(50, 50, 50, 1);
                line-height: 60px;
                text-align: center;
                padding: 29px;
                display: flex;
                flex-direction: column;
                align-items: center;

                .qr {
                    width: 360px;
                    height: 360px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }
            }

            .close {
                width: 74px;
                height: 74px;
                background: url('../../../static/img/guanb.png') no-repeat center center;
                background-size: 100% 100%;
                margin-top: 96px;
            }
        }
    }
</style>